var msCategoryAll   = 'full_series';
var slider;
var currentWorkPage = 1;
var category        = [];
var workLoading     = false;
var $grid;

$(document).ready(function () {
    getProductCategory();
    $.when(
        getProduct({
            data: {
                sW: [
                    {
                        sF: 'bRecommend',
                        sV: 0
                    }
                ]
            }
        })
    ).done(function () {
        resizeHeight();
        loadPage();
//        scrollingEffect();
    });
    blankHeight();

    $grid = $('.works-wrap').packery({
        itemSelector:    '.work-item',
        columnWidth:     '.grid-sizer',
        gutter:          0,
        // gutter: '.gutter-sizer',
        percentPosition: true,
        // isInitLayout:  false,
        // isResizeBound: false
    });

    resizeWorks();
});
$(window).load(function () {
});
var timeout;
$(window).scroll(function (e) {
    animated = false;
    clearTimeout(timeout);
    timeout = setTimeout(scrollMenu, 500);
});
$(window).resize(function (e) {
    resizeHeight();
    blankHeight();
    // resizeWorks();
//    if ($(window).width() >= 992) {
//        if ($('.hidden-mobile').is(':hidden')) {
//            $('.hidden-mobile').show();
//            $('.menu-btn').removeClass('active');
//        }
//    }
    //setImageCover($('.client img'));
});
$(window).bind('popstate', function (event) {

});
/*var s     = skrollr.init({
 forceHeight: false,
 mobileCheck: function () {
 //hack - forces mobile version to be off
 return false;
 }
 });*/
function resizeWorks() {
    // var iScale        = 0.6;
    // var padding       = parseInt($('.work-item').css('padding-right'));
    // var workListWidth = $('.holder').width() + padding;
    // $('.works-wrap').width(workListWidth);
    // var height  = Math.floor($('.work-item-sizer').innerWidth() * iScale);
    // var height2 = Math.floor($('.work-item.width2').innerWidth() * iScale);
    // var height3 = Math.floor($('.work-item.width3').innerWidth() * iScale);
    // var height4 = Math.floor($('.work-item.width4').innerWidth() * iScale);
    // if (height % 2 != 0) {
    //     height++;
    // }
    // if (height2 % 2 != 0) {
    //     height2++;
    // }
    // if (height3 % 2 != 0) {
    //     height3++;
    // }
    // if (height4 % 2 != 0) {
    //     height4++;
    // }

    // if ($(window).width() <= 480) {
    //     $('.work-item').height(height);
    // } else {
    //     $('.work-item').height(height);
    //     $('.work-item.width2').height(height2 + padding);
    //     $('.work-item.width3').height(height3 + padding + padding);
    //     $('.work-item.width4').height(height4 + padding);
    // }
    //$('.works-wrap').packery('shiftLayout');
    $('.works-wrap').packery();
    // setImageCover($('.work-item .content img'));
}

function blankHeight() {
//    $('.blank').height($('footer').height());
}

function scrollMenu() {
    if ($('#popup-slider').hasClass('active')) {
        history.replaceState(null, null, ($('.filter-btn.selected').attr('href') == '' ? getPath() + 'works/' + msCategoryAll : $('.filter-btn.selected').attr('href')) + (currentWorkPage > 1 ? '?page=' + currentWorkPage : ''));
        changeTitle('Works');
    }
}

function loadPage() {
    var loc      = history.location || document.location;
    var locStr   = loc.toString();
    var locQuery = locStr.replace(gsPath, '');
    var locQuery = locQuery.replace(sLangS + '/', '');
    var locArr   = locQuery.split('/');
    if (locArr[locArr.length - 1].indexOf('?') >= 0) {
        locArr[locArr.length - 1] = locArr[locArr.length - 1].substring(0, locArr[locArr.length - 1].indexOf('?'));
    }
    //console.log(locArr);

    if (locArr[0] != undefined) {
        if (locArr[0] == 'about' || locArr[0] == 'services') {
            var tempObj = {
                about:    'about',
                services: 'services'
            }
            showPopup($('#' + tempObj[locArr[0]]).html());
            $('#popup-slider').attr('data-tag', tempObj[locArr[0]]);
            $('.menu-' + tempObj[locArr[0]]).parent().toggleClass('selected');
            return;
        }
        if (locArr[0] == 'contact') {
            $('.menu-contact').trigger('click');
            return;
        }
        if (locArr[0] == 'works' && locArr[1] != undefined && locArr[1] != '') {
//            if (locArr[1] == msCategoryAll || locArr[1] == 'company' || locArr[1] == 'event' || locArr[1] == 'shopping_cart' || locArr[1] == 'reference') {
            if (locArr[1] == msCategoryAll || $.inArray(locArr[1], category) >= 0) {
                if (getQueryParameter('page') != null) {
                    page = getQueryParameter('page');
                    if ($.isNumeric(page)) {
                        page = parseInt(page);
                    } else {
                        page = 1;
                    }
                    currentWorkPage = 1;

                    if (locArr[1] != msCategoryAll) {
                        $('.filter-btn').removeClass('selected');
                        $('.filter-btn[href="' + locArr[1] + '"]').addClass('selected');
                    }

                    $('.work-item').remove();
                    settings     = {
                        data:      {
                            //sW: [
                            //    {
                            //        sF: 'bRecommend',
                            //        sV: 0
                            //    }
                            //]
                        },
                        iP:        currentWorkPage,
                        sCategory: (locArr[1] == msCategoryAll) ? '' : locArr[1]
                    };
                    var callback = function () {
                        if (currentWorkPage < page) {
                            currentWorkPage++;
                            settings['iP'] = currentWorkPage;
                            getProduct(settings, callback);
                        }
                    };
                    getProduct(settings, callback);
                    $('html, body').animate({
                        scrollTop: $('#part4-area').offset().top - $('header').height()
                    }, 1000, function () {

                    });
                    return;
                } else if (locArr[1] != msCategoryAll) {
                    filterWork(locArr[1]);
                }
                $('html, body').animate({
                    scrollTop: $('#part4-area').offset().top - $('header').height()
                }, 1000, function () {

                });
                return;
            } else if ($('[data-title=' + locArr[1] + ']').length > 0) {
                var obj = $('[data-title=' + locArr[1] + ']');
                $('html, body').animate({
                    scrollTop: $('#part4-area').offset().top - $('header').height()
                }, 1000, function () {
                    showPopup($(obj).data('data'));
                });
                return;
            } else {
                getProductById({id: locArr[1]});
                return;
            }
        }
        $('[data-title]').each(function (i, e) {
            if ($(e).attr('data-title') == locArr[0]) {
                $('html, body').animate({
                    scrollTop: $(e).offset().top - $('header').height()
                }, 1000);
            }
        });
    }
}

function resizeHeight() {
    var height = $(window).height();
    if ($(window).height() <= 992) {
        height = height - $('header').height();
    }
}

function getProductCategory(options) {
    var defaults = {
        id:  0,
        iP:  1,
        iPS: 16
    };
    var settings = $.extend(defaults, options);
    var options  = {
        method:   'GET',
        url:      gsPath + '/api/product_category',
        data:     {
            sFs: 'iCategoryID,iStatus,sCategoryKey',
            sW:  [
                {
                    sF: 'iCategoryGroupID=',
                    sV: '1'
                },
                {
                    sF: 'iCategoryLevel=',
                    sV: '1'
                },
                {
                    sF: 'iStatus=',
                    sV: '1'
                }
            ],
            sO:  [
                {
                    sF: 'iOrder',
                    sV: 'ASC'
                },
                {
                    sF: 'iCategoryID',
                    sV: 'DESC'
                }
            ],
            oD:  {
                languages: {
                    sDFs: 'iLanguageID,sName,sDesc',
                    sDO:  'iLanguageID-a'
                },
                products:  {
                    sDFs: 'iProductID',
                    sDW:  'tbShowRoomProducts.iStatus=1 AND tbShowRoomProducts.bRecommend=0'
                }
            },
            iP:  settings['iP'],
            iPS: settings['iPS']
        },
        dataType: 'json'//json/html
    };
    $.ajax(options)
        .done(function (data, textStatus, jqXHR) {
            //console.log(data);
            var obj   = data['aryResult']['aryData'];
            var aryID = [];
            $.each(obj, function (i, e) {
                if (typeof e[sLang] !== 'undefined' && e[sLang] !== false) {
                    category.push(e['sCategoryKey']);
                    $('.filter-wrap').append("| <a class='filter-btn' data-id='" + e['iCategoryID'] + "' data-key='" + e['sCategoryKey'] + "' data-count='" + Object.keys(e['products']).length + "' href='" + getPath() + "works/" + e['sCategoryKey'] + "' title='" + e[sLang]['sName'] + "'>" + e[sLang]['sName'] + "</a>");
                    //console.log(Object.keys(e['products']));
                    $.extend(aryID, e['products']);
                }
            });
            //console.log(Object.keys(aryID));
            $('[data-key=' + msCategoryAll + ']').attr('data-count', Object.keys(aryID).length);
        })
        .fail(function (jqXHR, textStatus, errorThrown) {
            console.log('HTTP ERROR' + jqXHR.status + ': ' + errorThrown);
        });
}

function getProduct(options, callback) {
    var defaults = {
        id:   0,
        iP:   1,
        iPS:  18,
        data: {}
    };
    var settings = $.extend(defaults, options);
    var options  = {
        method:   'GET',
        url:      gsPath + '/api/product',
        data:     {
            sC:  {
                sCategoryKey: (settings['sCategory'] && settings['sCategory'] != msCategoryAll) ? "'" + settings['sCategory'] + "'" : '',
                iStatus:      '1'
            },
            sFs: 'dtCreateTime,iProductID,iProductGroupID,sProductKey,decPrice,iStatus,sIcon,iValue01',
            sW:  [
                {
                    sF: 'iProductGroupID=',
                    sV: '1'
                },
                {
                    sF: 'iStatus=',
                    sV: '1'
                }
            ],
            sO:  [
                {
                    sF: 'iOrder',
                    sV: 'ASC'
                },
                {
                    sF: 'iProductID',
                    sV: 'DESC'
                }
            ],
            oD:  {
                languages:  {
                    sDFs: 'iLanguageID,sName,sDesc,sInfoValue03,sInfoValue04,sInfoValue05,sInfoValue06',
                    sDO:  'iLanguageID-a'
                },
                images:     {
                    sDFs: 'iProductImageID,iProductID,sImage',
                    sDW:  'iStatus=1',
                    sDO:  'iOrder-a,iProductImageID-d'
                },
                categories: {
                    sDFs: 'iCategoryID'
                }
            },
            iP:  settings['iP'],
            iPS: settings['iPS']
        },
        dataType: 'json'//json/html
    };
    if (checkNumber(settings['id']) > 0) {
        options['url'] = gsPath + '/api/product/' + settings['id'];
//        $.extend(options['data'], {
////                sPK:   'iProductID',
////            sDFs: 'iLanguageID,sName',
////            sDO: 'iLanguageID-a'
//        });
    }
    if (settings['data']['sW'])
        $.merge(options['data']['sW'], settings['data']['sW']);

    workLoading = true;
    $('#more-work').html(aryText.loading);
    $ajax = $.ajax(options)
        .done(function (data, textStatus, jqXHR) {
            //console.log(data);
            var fnHiddenMore = function () {
                $('#more-work').css({
                    display: 'none'
                });
            }

            var obj = data['aryResult']['aryData'];
            if (obj) {
                $.each(obj, function (i, e) {
                    if (typeof e[sLang] !== 'undefined' && e[sLang] !== false) {
                        var data = setWorkData(e);
//                        if (checkNumber(settings['id']) > 0) {
//                            return data;
//                        } else
                        var $item = $($('#work-template').tmpl(data));
                        $item.data('data', data);
                        $grid.append($item).packery('appended', $item);
                    }
                });

                if (settings['iP'] * settings['iPS'] >= $('[data-key=' + (settings['sCategory'] == '' ? msCategoryAll : settings['sCategory']) + ']').attr('data-count')) {
                    fnHiddenMore();
                } else {
                    $('#more-work').html(aryText.more_work);
                }

                resizeWorks();
                workLoading = false;
            } else {
                if (checkNumber(settings['id']) > 0) {
                    return false;
                }
                fnHiddenMore();
            }

            if ($.isFunction(callback)) {
                callback();
            }
        })
        .fail(function (jqXHR, textStatus, errorThrown) {
            console.log('HTTP ERROR' + jqXHR.status + ': ' + errorThrown);
        });
    return $ajax;
}

function getProductById(options) {
    var defaults = {
        id:   0,
        iP:   1,
        iPS:  16,
        data: {}
    };
    var settings = $.extend(defaults, options);
    var options  = {
        method:   'GET',
        url:      gsPath + '/api/product',
        data:     {
            sC:  {
                sCategoryKey: (settings['sCategory']) ? "'" + settings['sCategory'] + "'" : '',
                iStatus:      '1'
            },
            sFs: 'dtCreateTime,iProductID,iProductGroupID,sProductKey,decPrice,iStatus,sIcon,iValue01',
            sW:  [
                {
//                        sF: 'iProductGroupID>',
                    sF: 'iProductGroupID=',
                    sV: '1'
                },
                {
                    sF: 'iStatus=',
                    sV: '1'
                }
            ],
            sO:  [
                {
                    sF: 'iOrder',
                    sV: 'ASC'
                },
                {
                    sF: 'iProductID',
                    sV: 'DESC'
                }
            ],
            oD:  {
                languages:  {
                    sDFs: 'iLanguageID,sName,sDesc,sInfoValue03,sInfoValue04,sInfoValue05,sInfoValue06',
                    sDO:  'iLanguageID-a'
                },
                images:     {
                    sDFs: 'iProductImageID,iProductID,sImage',
                    sDW:  'iStatus=1',
                    sDO:  'iOrder-a,iProductImageID-d'
                },
                categories: {
                    sDFs: 'iCategoryID'
                }
            },
            iP:  settings['iP'],
            iPS: settings['iPS']
        },
        dataType: 'json'//json/html
    };
    if (checkNumber(settings['id']) > 0) {
        options['url'] = gsPath + '/api/product/' + settings['id'];
//        $.extend(options['data'], {
////                sPK:   'iProductID',
////            sDFs: 'iLanguageID,sName',
////            sDO: 'iLanguageID-a'
//        });
    }
    if (settings['data']['sW'])
        $.merge(options['data']['sW'], settings['data']['sW']);
    $.ajax(options)
        .done(function (data, textStatus, jqXHR) {
            var obj = data['aryResult']['aryData'];
            if (obj != false) {
                if (typeof obj[sLang] !== 'undefined' && obj[sLang] !== false) {
                    var data = setWorkData(obj);
                    try {
                        $('html, body').animate({
                            scrollTop: $('#part4-area').offset().top - $('header').height()
                        }, 1000);
                    } catch (err) {
                    }
                }
            }
        })
        .fail(function (jqXHR, textStatus, errorThrown) {
            console.log('HTTP ERROR' + jqXHR.status + ': ' + errorThrown);
        });
}

function setWorkData(obj) {
    //console.log(obj);

    var slide = [];
    if (obj['images'] != null) {
        $.each(obj['images'], function (x, z) {
            slide.push(z['sImage']);
        });
    } else {
        slide = false;
    }
    var data = {
        id:        obj['iProductID'],
        key:       obj['sProductKey'],
        width:     (obj["iValue01"] == 1) ? '' : 'width' + obj["iValue01"],
        cat:       Object.keys(obj['categories']),
        title:     getStrReplaceCode(obj[sLang]["sName"]),
        name:      obj[sLang]["sName"],
        content:   obj[sLang]["sDesc"],
        link:      obj[sLang]["sInfoValue03"],
        icon:      obj["sIcon"],
        slide:     slide,
        challenge: obj[sLang]["sInfoValue04"],
        solution:  obj[sLang]["sInfoValue05"],
        service:   obj[sLang]["sInfoValue06"]
    };
    return data;
}

function filterWork(category) {
    currentWorkPage = 1;
    $('html, body').animate({
        scrollTop: $('#part4-area').offset().top - $('header').height()
    }, 1000);
    $('.work-item').remove();

    getProduct({
        data:      {
            sW: [
                {
                    sF: 'bRecommend',
                    sV: 0
                }
            ]
        },
        sCategory: category
    });

    var sLink = getPath() + 'works/' + category;
    $('#more-work').attr('href', setQueryString('page', 2, sLink));
    history.replaceState(null, null, sLink);

//    resizeWorks();
    $('.filter-btn').removeClass('selected');
    $('[data-key=' + category + ']').addClass('selected');
    $('#more-work').css({
        display: 'initial'
    });
//    if (category == msCategoryAll) {
////        $('.work-item').fadeIn(200, function () {
////            setImageCover($('.work-item .content img'));
////            $grid.packery();
////        });window.location.href
//
//        getProduct({data: {sW: [{sF: 'bRecommend', sV: 0}]}});
//    } else {
//        getProduct({data: {sW: [{sF: 'bRecommend', sV: 0}]}, sCategory: category});
//    }
//    resizeWorks();
}

$(function () {
    animated = false;
    $('.menu li a[scrollto], .menu li a[data-tag], .menu li a.menu-contact').click(function (e) {
        e.preventDefault();
    });

    $('.filter-wrap').delegate('.filter-btn', 'click', function (e) {
        e.preventDefault();
//        $('.filter-btn').removeClass('selected');
//        $(this).addClass('selected');
        filterWork($(this).attr('data-key'));
    });
    var isLoading = false;
    var imgArr    = [];
    $('.works-wrap').delegate('.work-item', 'click', function () {
//        if (!isLoading) {
//            isLoading = true;
        var data = $(this).data('data');
//            var slide = $(this).data('data')['slide'];
//            $('body').on('image-loaded', function () {
//                if (imgArr.length == slide.length) {
        if ($('#popup-slider').hasClass('active')) {
            showPopup(data);
            $('#popup-slider').attr('data-tag', 'work');
        }
//                    $('body').off('image-loaded');
//                    isLoading = false;
//                    imgArr = [];
//                }
//            });
//            if (slide.length > 0) {
//                $.each(slide, function (i, e) {
//                    var o = new Image;
//                    o.src = e, $(o).load(function () {
//                        imgArr.push(true);
//                        $('body').trigger("image-loaded");
//                    });
//                });
//            }
//        } else {
//            imgArr = [];
//        }
    });
    $('.works-wrap').delegate('.work-link', 'click', function (e) {
        e.preventDefault();
    });
    $('#more-work').click(function (e) {
        e.preventDefault();
        if (!workLoading) {
            currentWorkPage++;
            $(this).html('Loading');
            //var sLink = getPath() + $('#part3-area').attr('data-title') + ($('.filter-btn.selected').attr('href') == '' ? '/' + msCategoryAll : '/' + $('.filter-btn.selected').attr('href')) + (currentWorkPage > 1 ? '?page=' + currentWorkPage : '');
            var sLink = setQueryString('page', currentWorkPage, ($('.filter-btn.selected').attr('href') == '' ? getPath() + 'works/' + msCategoryAll : $('.filter-btn.selected').attr('href')));
            $('#more-work').attr('href', setQueryString('page', currentWorkPage + 1, sLink));
            history.replaceState(null, null, sLink);
            getProduct({
                data:      {
                    sW: [
                        {
                            sF: 'bRecommend',
                            sV: 0
                        }
                    ]
                },
                iP:        currentWorkPage,
                sCategory: $('.filter-btn.selected').attr('href')
            });
            //} else {
            //    return;
        }
    });
    $('#popup-slider').delegate('.slider-left', 'click', function () {
        $(slider).trigger('prev.owl.carousel');
    });
    $('#popup-slider').delegate('.slider-right', 'click', function () {
        $(slider).trigger('next.owl.carousel');
    });
});